package com.java2nb.novel.core.utils;

import org.springframework.http.*;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;

/**
 * @author Administrator
 */
public class HttpUtil {

    private static RestTemplate restTemplate = RestTemplateUtil.getInstance("utf-8");


    public static String getByHttpClient(String url) {
        try {

            ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
            if (forEntity.getStatusCode() == HttpStatus.OK) {
                return forEntity.getBody();
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getByHttpClientWithChrome(String url) {
        try {

            HttpHeaders headers = new HttpHeaders();
            headers.add("user-agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.67 Safari/537.36");
            HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
            ResponseEntity<String> forEntity = null;

            for (int i = 0; i < 10; i++) {
                try {
                    forEntity = restTemplate.exchange(url.toString(), HttpMethod.GET, requestEntity, String.class);
                } catch (HttpServerErrorException | ResourceAccessException e1) {
                    // System.out.println(String.format("异常捕获，重试次数：%d ...", i+1));
                    Thread.sleep(1000);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                if (null != forEntity && forEntity.getStatusCode() == HttpStatus.OK) {
                    return forEntity.getBody();
                }
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 采集整个网页html页面
    public static void main(String[] args) {
        String s = getByHttpClientWithChrome("http://m.mcmssc.com/xclass/1/1.html");
        System.out.println(s);
    }
}
